package utils

import (
	"time"
)

var (
	localTz, _ = time.LoadLocation("Asia/Shanghai")
)

func GetNowTs() int {
	return int(time.Now().Unix())
}

func GetStartTimeOfToday() int {
	now := time.Now().In(localTz)
	startTime := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, localTz)
	return int(startTime.Unix())
}

func GetStartTimeofTomorow() int {
	return GetStartTimeOfToday() + 86400
}

func GetDayStartTimeFromTs(ts int64) int {
	tm := time.Unix(ts, 0).In(localTz)
	startTime := time.Date(tm.Year(), tm.Month(), tm.Day(), 0, 0, 0, 0, localTz)
	return int(startTime.Unix())
}

func GetDayStartTimeFromTime(t time.Time) int {
	startTime := time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, localTz)
	return int(startTime.Unix())
}

func GetTimeFromTimestamp(ts int64) time.Time {
	return time.Unix(ts, 0).In(localTz)
}

func GetTimeNow() time.Time {
	return time.Now().In(localTz)
}

func GetTimeFromStr(format, s string) time.Time {
	t, e := time.ParseInLocation(format, s, localTz)
	if e != nil {
		return GetTimeNow()
	}
	return t.In(localTz)
}

func GetYMD(tNow time.Time) int {
	m := int(tNow.Month())
	y := tNow.Year()

	return y*10000 + m*100 + tNow.Day()
}

func GetStartTimeOfWeek() int {
	now := GetTimeNow()
	//now = GetTimeFromStr("20060102 15:04:05", "20240817 09:10:00")
	weekday := int(now.Weekday())
	if weekday == 0 {
		weekday = 7
	}
	monday := now.Add(24*time.Hour - time.Duration(weekday)*24*time.Hour)
	monday = time.Date(monday.Year(), monday.Month(), monday.Day(), 0, 0, 0, 0, localTz)
	return int(monday.Unix())
}

func GetStartTimeOfMonth() int {
	now := GetTimeNow()
	//now = GetTimeFromStr("20060102 15:04:05", "20240817 09:10:00")
	firstday := time.Date(now.Year(), now.Month(), 1, 0, 0, 0, 0, localTz)
	return int(firstday.Unix())
}

func GetStartTimeOfNextMonth() int {
	now := GetTimeNow()
	now = GetTimeFromStr("20060102 15:04:05", "20241217 09:10:00")
	year := now.Year()
	month := (now.Month() + 1) % 12
	if month == 1 {
		year += 1
	}
	firstday := time.Date(year, month, 1, 0, 0, 0, 0, localTz)
	return int(firstday.Unix())
}
